package com.atguigu.cloud.controller;

import com.atguigu.cloud.entities.PayDTO;
import com.atguigu.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * ClassName:OrderController
 * Package:com.atguigu.cloud.controller
 * Description:
 *
 * @Author:@郭先森
 * @Create:2025/6/19 - 16:35
 * @Version:v1.0
 */
@RestController
public class OrderController {
    //public static final String PaymentServer_URL="http://localhost:8001";//先写死,硬编码
    //有了服务注册中心以后就可以不用写死了
    public static final String PaymentServer_URL="http://cloud-payment-service";//服务注册中心上的微服务

    @Resource
    private RestTemplate restTemplate;
    @GetMapping(value = "/consumer/pay/add")
    public ResultData addOrder(PayDTO payDTO){
        return restTemplate.postForObject(PaymentServer_URL + "/pay/add", payDTO, ResultData.class);
    }


    //删除和修改自己不写,随后再写



    //按照id获得订单模块
    @GetMapping(value = "/consumer/pay/get/{id}")
    public ResultData getPayInfo(@PathVariable("id") Integer id){
        return restTemplate.getForObject(PaymentServer_URL+"/pay/get/"+id,ResultData.class,id);
    }

    //查询所有订单模块
    @GetMapping(value = "/consumer/pay/get")
    public ResultData getAll(){
        return restTemplate.getForObject(PaymentServer_URL+"/pay/get",ResultData.class);
    }

    @GetMapping(value = "/consumer/pay/get/info")
    private String getInfoByConsul()
    {
        return restTemplate.getForObject(PaymentServer_URL + "/pay/get/info", String.class);
    }


    @Resource
    private DiscoveryClient discoveryClient;
    @GetMapping("/consumer/discovery")
    public String discovery()
    {
        //查询可用地的服务列表
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println(element);
        }

        System.out.println("===================================");

        //只要cloud-payment-service，做负载均衡就在这俩上
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance element : instances) {
            System.out.println(element.getServiceId()+"\t"+element.getHost()+"\t"+element.getPort()+"\t"+element.getUri());
        }

        return instances.get(0).getServiceId()+":"+instances.get(0).getPort();
    }
}
